package com.cskaoyan.jdbc.transfer;

import com.cskaoyan.jdbc.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 创建日期: 2022/05/13 14:48
 *
 * @author ciggar
 *
 * 转账案例：模拟事务
 */
public class TransferDemo {

    static Connection connection;

    static {
        connection = JDBCUtils.getConnection();
    }


    public static void main(String[] args) throws SQLException {

        Boolean ret = transfer("风华哥", "孙悟空", 2000);
        if (ret) {
            System.out.println("转账成功，工资到账，关机！下班");
        }else {
            System.out.println("转账失败，风华哥没钱了，赶紧跑路！");
        }

    }


    //  转账的方法
    /**
     * 创建日期：2022/05/13 14:50
     * @param fromName  转账发起人
     * @param toName    转账受益人
     * @param money     转账金额
     * @return java.lang.Boolean
     * @author ciggar
     */
    public static Boolean transfer(String fromName,String toName,Integer money) throws SQLException {


        // 开启事务
        connection.setAutoCommit(false);

        try {

            // 给发起人的账户扣钱
            PreparedStatement preparedStatement = connection.prepareStatement("update account set money = money - ? where name = ? and money >= ?");

            preparedStatement.setInt(1, money);
            preparedStatement.setString(2, fromName);
            preparedStatement.setInt(3, money);

            // 执行SQL
            int affectedRows = preparedStatement.executeUpdate();

            if (affectedRows == 0) {
                System.out.println("扣钱失败！");
                return false;
            }


//            int i = 1 / 0;


            // 给受益人的账户加钱
            PreparedStatement preparedStatement2 = connection.prepareStatement("update account set money = money + ? where name = ?");

            preparedStatement2.setInt(1, money);
            preparedStatement2.setString(2, toName);

            // 执行SQL
            int affectedRows2 = preparedStatement2.executeUpdate();
            if (affectedRows2 == 0) {
                System.out.println("加钱失败！");
                throw new RuntimeException("RuntimeException加钱失败!");
            }

        }catch (Exception ex) {

            ex.printStackTrace();

            // 回滚事务
            connection.rollback();
            return false;
        }

        // 提交事务
        connection.commit();
        return true;

    }


}
